import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:media_kit/media_kit.dart';
import 'package:series_play/utils/log.dart';
import 'package:series_play/widget/app_color.dart';

class VideoProgressBar extends StatefulWidget {
  const VideoProgressBar({super.key, required this.player});

  final Player player;

  @override
  State<VideoProgressBar> createState() => _VideoProgressBarState();
}

class _VideoProgressBarState extends State<VideoProgressBar> {
  bool _dragging = false;
  double _dragValue = 0;

  @override
  Widget build(BuildContext context) {

    // 更新
    return StreamBuilder<Duration>(
      stream: widget.player.stream.position,
      builder: (context, posSnap) {
        final position = posSnap.data ?? Duration.zero;

        return StreamBuilder<Duration?>(
          stream: widget.player.stream.duration,
          builder: (context, durSnap) {
            final duration = durSnap.data ?? Duration.zero;
            final max = duration.inMilliseconds.toDouble();

            // 当前滑块值（拖动时使用拖动值，否则用播放位置）
            final value = _dragging
                ? _dragValue
                : position.inMilliseconds.clamp(0, max).toDouble();

            return SizedBox(
              height: 8.w,
              child: Slider(
                min: 0,
                max: max <= 0 ? 1 : max,
                value: value,
                activeColor: AppColor.primary,
                inactiveColor: Colors.white54,
                thumbColor: Colors.white,

                onChangeStart: (v) {
                  setState(() {
                    _dragging = true;
                    _dragValue = v;
                  });
                },
                onChanged: (v) {
                  setState(() {
                    _dragValue = v;
                  });
                },
                onChangeEnd: (v) async {
                  setState(() => _dragging = false);
                  await widget.player.seek(Duration(milliseconds: v.toInt()));
                },
              ),
            );
          },
        );
      },
    );
  }

  String _fmt(Duration d) {
    String two(int n) => n.toString().padLeft(2, '0');
    final h = d.inHours;
    final m = d.inMinutes.remainder(60);
    final s = d.inSeconds.remainder(60);
    return h > 0 ? "${two(h)}:${two(m)}:${two(s)}" : "${two(m)}:${two(s)}";
  }
}
